package ua.org.nuos.sdms.middle.service;

import org.apache.commons.lang.Validate;
import ua.org.nuos.configuration.SdmsConfiguration;
import ua.org.nuos.sdms.middle.vo.CustomMessage;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 23.10.11
 * Time: 17:26
 * To change this template use File | Settings | File Templates.
 */
@LocalBean
@Stateless
public class MailSenderServiceBean {

    @EJB(beanName = "SdmsConfiguration")
    protected SdmsConfiguration configuration;

    public void sendMessage(CustomMessage message) {
        try {
            Validate.notNull(message, "message can not be null");
            Validate.notNull(message.getRecipientList(), "recipient list can not be null");

            Session session = getSession();

            MimeMessage msg = new MimeMessage(session);
            if (message.getSubject() != null) {
                try {
                    msg.setSubject(MimeUtility.encodeText(message.getSubject(), "utf-8", "Q"));
                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(MailSenderServiceBean.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if ((message.getReplyTo() != null) && (!message.getReplyTo().isEmpty())) {
                Address[] replyToAddresses = new InternetAddress[message.getReplyTo().size()];
                for (int i = 0; i < message.getReplyTo().size(); i++) {
                    replyToAddresses[i] = new InternetAddress(message.getReplyTo().get(i));
                }
                msg.setReplyTo(replyToAddresses);
            }
            msg.setFrom(new InternetAddress(message.getFrom()));
            for (String recipient : message.getRecipientList()) {
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            }
            String type = "text/plain; charset=utf-8"; //default value of content type
            if (message.getContentType() != null) {
                type = message.getContentType();
            }

            Multipart content = new MimeMultipart();
            MimeBodyPart textContent = new MimeBodyPart();
            textContent.setContent(message.getContent(), type);
            content.addBodyPart(textContent);

            if (message.getFile() != null) {
                MimeBodyPart fileContent = new MimeBodyPart();
                FileDataSource fileDs = new FileDataSource(message.getFile().getContent());
                fileContent.setDataHandler(new DataHandler(fileDs));
                fileContent.setFileName(message.getFile().getNameToSave());
                content.addBodyPart(fileContent);
            }
            msg.setContent(content);

            Transport.send(msg);
        } catch (MessagingException ex) {
            Logger.getLogger(MailSenderServiceBean.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex.getMessage());
        }


    }

    private Session getSession() {
        Authenticator authenticator = new Authenticator();
        return Session.getInstance(configuration.getGmailProperties(), authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator {

        private PasswordAuthentication authentication;

        public Authenticator() {
            String username = configuration.getGmailSenderUser();
            String password = configuration.getGmailSenderPassword();
            authentication = new PasswordAuthentication(username, password);
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

}
